package com.hfh.homework;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author hfh
 * @Date 2022 09 14 14 19
 **/
public class Work1 {
    @Test
    public void client() throws IOException {
        Socket s = new Socket(InetAddress.getLocalHost(),6666);

        PrintWriter pw = new PrintWriter(s.getOutputStream());
        BufferedReader br =new BufferedReader(new InputStreamReader(s.getInputStream()));
        Scanner sc = new Scanner(System.in);
        while (true){
            String str = sc.next();
            pw.println(str);
            pw.flush();

            String resp = br.readLine();
            System.out.println(resp);
            if ("exit".equals(str)) {
                break;
            }
        }
        pw.close();
        sc.close();
        s.close();
    }

    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(6666);
        Socket s = ss.accept();

        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter pw =new PrintWriter(s.getOutputStream());

        while (true){
            String msg = br.readLine();
            pw.println("您的信息已收到");
            pw.flush();

            if ("exit".equals(msg)) {
                System.out.println("bye");
                break;
            } else {
                System.out.println(msg);
            }
        }
        br.close();
        s.close();
        ss.close();
    }
}
